﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VirtualPress.Portal.Biz;
using System.IO;
using System.Drawing;
using VirtualPress.Portal.WebLogic;
using VirtualPress.Infrastructure.Entities.Entity;
using VirtualPress.Tool.Configration;
using VirtualPress.Tool.Framework;
using VirtualPress.Portal.Web.Models;
using VirtualPress.Infrastructure.Entities.JSONModel;
using VirtualPress.Infrastructure.Entities.Enum;
using VirtualPress.Infrastructure.HitMonitor;

namespace VirtualPress.Portal.Web.Controllers
{
#if !DEBUG
    [ErrorHandle]
#endif
    [Compress]
    public class HomeController : SiteBaseController
    {        
        public ActionResult Index()
        {
            ViewBag.News = iCache.Get("CommonBiz.GetAllNews_SiteNews_0_5", () => { return CommonBiz.GetAllNews(NewsType.SiteNews, 0, OrganizationType.System, 0, 5); }, 600);
            ViewBag.Journals = iCache.Get("JournalBiz.GetJournalSnapshot", 
                () => { return JournalBiz.GetJournalSnapshot(
                    SiteResource.HomeJournals.Select(c => Int32.Parse(c)).ToList());
                }, 600);
            ViewBag.PublishArticle = iCache.Get("JournalBiz.GetAllArticleSnapshot_0_6",
                () => { return JournalBiz.GetAllArticleSnapshot(0, 6); }, 600);
            return View();
        }
        public void commonUpload()
        {
            var file = System.Web.HttpContext.Current.Request.Files[0];
            string result = "";
            string basedir = "/content/commonImage/";
            string filePath = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                if (!System.IO.Directory.Exists(HttpContext.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Server.MapPath(basedir));
                }
                var fileinfo = new FileInfo(file.FileName);
                filePath = basedir + Guid.NewGuid().ToString() + fileinfo.Extension;
                file.SaveAs(HttpContext.Server.MapPath(filePath));
            }
            if (!String.IsNullOrEmpty(filePath))
            {
                result = new
                {
                    url = filePath,
                    title = "",
                    original = "",
                    state = "SUCCESS"
                }.ToJson();
                HttpContext.Response.Write(result);
            }
        }
        public void SWFPrepareUpload()
        {
            new UploadTool().SWFPrepareUpload();
        }

        public ActionResult badrequest()
        {
            return View();

        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Agreement()
        {
            return View();
        }
        public ActionResult Apply()
        {
            return View();
        }

        public ActionResult News(int page=0)
        {
            var data = CommonBiz.GetAllNews( NewsType.SiteNews,0, OrganizationType.System,page, 20);
            ItemListBox<News> list = new ItemListBox<News>();
            if (data != null)
            {
                list.Data = data;
                list.BuildPage(CommonBiz.GetAllNewsForPage(0, OrganizationType.System, NewsType.SiteNews),
                    page, 20, new PageParameter()
                    {
                        Param_page = "page",
                        IsActive = false,
                        Style = "home"
                    });
            }
            ViewBag.News = list;
            return View();
        }
        public ActionResult NewsDetails(int id)
        {
            var item = new News().Find(id.ToString());
            if (item == null)
            {
                return Redirect("/home/news");
            }
            ViewBag.Data = item;
            return View();
        }

        public ActionResult Error()
        {
            return View();
        }

        /// <summary>
        /// 当前登录角色不对。要求换用普通用户登录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult invalid(int id)
        {
            ViewBag.Id = id;
            return View();
        }
        [HttpPost]
        public ActionResult invalid(int id,string more)
        {
            System.Web.Security.FormsAuthentication.SignOut();
            return Redirect("/WorkSpace/member/Contribute?journal=" + id);
        }
        public ActionResult Search()
        {
            return View();
        }
        public ActionResult Expert()
        {
            return View();
        }
        public ActionResult SubmitFlow()
        {
            return View();
        }
        public ActionResult PublishFlow()
        {
            return View();
        }
        public ActionResult CreateJournalFlow()
        {
            return View();
        }
        public ActionResult CreateMeetingFlow()
        {
            return View();
        }
        public ActionResult PublishingNotice()
        {
            return View();
        }
        public ActionResult Members()
        {
            return View();
        }
        public ActionResult declinereview(string token)
        {
            string resource = EncodeByBase64.Decode(token);
            if (String.IsNullOrEmpty(resource))
            {
                return RedirectToAction("ReceivePostDataError");
            }
            resource = AesAlgorithm.Decrypt(resource);
            if (String.IsNullOrEmpty(resource))
            {
                return RedirectToAction("ReceivePostDataError");
            }
            ExamineTokenModel model = resource.ToObject<ExamineTokenModel>();
            if (model == null)
            {
                return RedirectToAction("ReceivePostDataError");
            }
            var record = new AuditingRecord().Find(model.ExamineId.ToString());
            record.ExamineFinishDate = DateTime.Now;
            record.ExamineStatus = ExamineStatus.Decline;
            record.PostModify();
            return View();
        }
        public ActionResult ReceivePostData(string token)
        {
            string resource = EncodeByBase64.Decode(token);
            if (String.IsNullOrEmpty(resource))
            {
                return RedirectToAction("ReceivePostDataError");
            }
            resource = AesAlgorithm.Decrypt(resource);
            if (String.IsNullOrEmpty(resource))
            {
                return RedirectToAction("ReceivePostDataError");
            }
            ExamineTokenModel model = resource.ToObject<ExamineTokenModel>();
            if (model == null)
            {
                return RedirectToAction("ReceivePostDataError");
            }
            var expert = new Expert().Find(model.expertUsername);
            var article = new Article().Find(model.ArticleId.ToString());
            var record = new AuditingRecord().Find(model.ExamineId.ToString());
            if (expert == null || article == null || record == null)
            {
                return RedirectToAction("ReceivePostDataError");
            }
            if (record.ExamineStatus != Infrastructure.Entities.Enum.ExamineStatus.DaiShenHe)
            {
                return RedirectToAction("ExamineIsFinish", new { type = (int)record.ExamineStatus });
            }
            ViewBag.Expert = expert;
            ViewBag.Article = article;
            ViewBag.User = new User().Find(expert.UserName);
            if (article.ArticleType == ArticleType.Journal)
            {
                ViewBag.Journal = new Periodical().Find(article.Peri_Id.ToString());
            }
            else
            {
                ViewBag.Meeting = new Meeting().Find(article.Conference_Id.ToString());
            }
            ViewBag.ExamineId = model.ExamineId;

            ViewBag.Authors = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            return View();
        }
        public ActionResult ReceivePostDataError()
        {
            return View();
        }
        public ActionResult ExamineIsFinish(int type)
        {
            ViewBag.Type = type;
            return View();
        }
        [HttpPost]
        public ActionResult ReceivePostData(int examineId, int articleId, string expert, 
            string type,string Originality,string Usefulness,string Soundness,string LinguisticQuality,
            string resolution,string contribution,string originalless,
            int verdict, string verdictcontent)
        {
            JournalBiz.DoReceiveExamineSheet(examineId, articleId, expert, 
                type, Originality, Usefulness, Soundness, LinguisticQuality,
             resolution, contribution, originalless, verdict, verdictcontent, "examineSheet");
            return RedirectToAction("ReceivePostDataSuccess");
        }
        public ActionResult ReceivePostDataSuccess()
        {
            return View();
        }
        public ActionResult PublishApply()
        {
            return View();
        }
        [HttpPost]
        public ActionResult PublishApply(string name, string authors, string field,
            string way, string phone, string contact, 
            string mail, string introduction)
        {
            CommonBiz.NewPublishApply(
                new PublishApply()
                {
                    Name = name,
                    Authors = authors,
                    Field = field,
                    Phone = phone,
                    Contact = contact,
                    Way = way,
                    Mail = mail,
                    Introduction = introduction,
                    ApplyTime = DateTime.Now
                });
            return RedirectToAction("PublishApplySuccess");
        }
        public ActionResult PublishApplySuccess() 
        {
            return View();
        }

        public ActionResult TempleteForm()
        {
            return View();
        }

        #region 会议
        public ActionResult conference(int type = 0, int page = 0)
        {
            var meetings = new Meeting().FindAll(
                c => c.isActive && c.isInstall, c => c.Id, 0, 10);
            var data = new ItemListBox<Meeting>(meetings).BuildPage(
                new Meeting().Count(c => c.isActive && c.isInstall), 0, 10, new PageParameter() { Style = "home" });
            ViewBag.Meetings = data;
            return View();
        }
        #endregion

        public ActionResult Cooperation()
        {
            return View();
        }
    }
}
